package org.ds.blog.controller;

import org.ds.blog.model.CustomCode;
import org.ds.blog.model.Response;
import org.ds.blog.model.User;
import org.ds.blog.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author glx
 */
@RestController
public class AuthController {
    @Autowired
    private AuthService authService;

    @PostMapping("/user/login")
    public Response login(@Valid @RequestBody User user) {
        String token = authService.login(user.getUsername(), user.getPassword());
        return Response.ok().message("登录成功").data(token);
    }

    @PostMapping("/user/register")
    public Response register(@Valid @RequestBody User user) {
        User register = authService.register(user);
        if (register == null) {
            return Response.fail().code(CustomCode.USER_EXIST.getCode()).message(CustomCode.USER_EXIST.getMessage());
        }
        return Response.ok().code(CustomCode.SUCCESS.getCode()).data(register);
    }
}
